package com.aishang.excelform.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cmp
 */
public class HtmlDataUtil {
    private static final Logger logger = LoggerFactory.getLogger(HtmlDataUtil.class);

    public static final String MUST = "${m}";
    public static final String DISABLED = "${disabled}";
    private static final String COPY = "${c}";
    public static final String MAXLENGTH = "\\$\\{max\\{([0-9]+)}}";
    private static final String ONEINPUT = "${/}";
    private static final String DATETIME = "${date}";
    private static final String MANYINPUT = "${//}";
    private static final String OKINPUT = "${?}";
    private static final String COMPANYSELECT = "${s{八局、四局、五局}}";
    private static final String TIMEINPUT = "${ts-te}";
    private static final String FILEINPUT = "${Signatures}";
    private static final String RAHKSELECT = "${s{优秀、合格、不合格}}";
    private static final String URLPRJID = "${url{prjid}}";
    private static final String VPRJID = "${v{prjid}}";
    private static final String PROJECTNAME = "${ProjectName}";
    private static final String PROJECTCODE = "${ProjectCode}";
    private static final String BUILDUNIT = "${BuildUnit}";
    private static final String SUPERVISIONUNIT = "${SupervisionUnit}";
    private static final String EPCUNIT = "${EPCUnit}";
    private static final String CONSTRUCTIONUNIT = "${ConstructionUnit}";
    private static final String DESIGNUNIT = "${DesignUnit}";
    private static final String SURVEYUNIT = "${SurveyUnit}";
    private static final String DETECTAGENCY = "${DetectAgency}";
    private static final String QUALITYDETECTAGENCY = "${QualityDetectAgency}";
    private static final String UNITPROJECT = "${UnitProject}";
    private static final String TEMPLATE = "${Template}";
    private static final String ATTACHMENTS = "${attachments}";
    //动态多选框匹配符：${checkbox(文字1, 文字2, 文字3，...文字N)}  ps:"文字1, 文字2, 文字3，...文字N"为动态文字部分
    private static final String CHECKBOX = "${checkbox(";
    //动态下拉框匹配符：${select(文字1, 文字2, 文字3，...文字N)}  ps:"文字1, 文字2, 文字3，...文字N"为动态文字部分
    private static final String SELECT = "${select(";
    //表单编号
    private static final String FORMCODE = "${FormCode}";

    //带input事件的单行输入框，例如 ${:(E1)}， E1为input回调的对应单元格
    public static final String ONEINPUTINPUTEVENT = "${:";


    private static final String VALUETAG = "1";
    private static final String PLACETAG = "0";
    public static final Integer NUM6 = 6;
    public static final String SAVETAG = "saveTag";

    public static String readfile(String filePath) {
        File file = new File(filePath);
        InputStream input = null;
        try {
            input = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuffer buffer = new StringBuffer();
        byte[] bytes = new byte[1024];
        try {
            for (int n; (n = input.read(bytes)) != -1; ) {
                buffer.append(new String(bytes, 0, n, "UTF-8"));
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    /**
     * 获取body
     */
    public static String getbody(String htm) {
        String start = "<body";
        String end = "</body>";
        int a = htm.indexOf(start);
        int b = htm.indexOf(end) + end.length();
        if (a != -1 && b != NUM6) {
            return htm.substring(a, b);
        }
        return htm;
    }


    /**
     * 解析html
     *
     * @param body
     * @return
     */
    public static String changeHtml(String body) {
        String res = body;
        String regex = ">\\s*\\$\\{.*?\\}.*?<";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(res);
        int i = 1, y = 0;
        while (m.find()) {
            String htmlReplacement = getHtmlReplacement(m.group(0), i, y);
            res = res.replaceFirst(regex, htmlReplacement);
            i++;
            if (m.group(0).contains(FILEINPUT)) {
                y++;
            }
        }
        return res;

    }


//    /**
//     * 解析html，加统计需签章次数
//     * @param body
//     * @param y
//     * @return
//     */
//    public static String changeHtml(String body, int y) {
//        String res = body;
//        String regex = ">\\s*\\$\\{.*?\\}.*?<";
//        Pattern p = Pattern.compile(regex);
//        Matcher m = p.matcher(res);
//        int i = 1;
//        while(m.find()) {
//            String htmlReplacement = getHtmlReplacement(m.group(0),i, y);
//            res = res.replaceFirst(regex,htmlReplacement);
//            i++;
//            if(m.group(0).contains(FILEINPUT)){ y++; }
//        }
//        return res;
//
//    }

    /**
     * 解析统计需签章次数
     *
     * @param body
     * @return
     */
    public static int countSignatureNumber(String body) {
        String res = body;
        String regex = ">\\s*\\$\\{.*?\\}.*?<";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(res);
        int y = 0;
        while (m.find()) {
            if (m.group(0).contains(FILEINPUT)) {
                y++;
            }
        }
        return y;
    }

    /**
     * 解析统计表单编号数量
     *
     * @param body
     * @return
     */
    public static int countFormCodeNumber(String body) {
        String res = body;
        String regex = ">\\s*\\$\\{.*?\\}.*?<";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(res);
        int y = 0;
        while (m.find()) {
            if (m.group(0).contains(FORMCODE)) {
                y++;
            }
        }
        return y;
    }


    /**
     * 根据标识获取id
     *
     * @param tag
     * @param i
     * @return
     */
    public static List<String> getValueId(String tag, int i) {
        List<String> list = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        if (tag.contains(ONEINPUT)) {
            sb.append("input").append(i);
        } else if (tag.contains(MANYINPUT)) {
            sb.append("textarea").append(i);
        } else if (tag.contains(OKINPUT)) {
            sb.append("right").append(i);
        } else if (tag.contains(COMPANYSELECT)) {
            sb.append("company").append(i);
        } else if (tag.contains(TIMEINPUT)) {
            sb.append("datas").append(i);
            sb2.append("datas").append(i + 10000);
        } else if (tag.contains(FILEINPUT)) {
//            sb.append("boss").append(i);
//            sb2.append("previewImg").append(i);
            sb.append("signatures").append(i);
        } else if (tag.contains(RAHKSELECT)) {
            sb.append("rank").append(i);
        } else if (tag.contains(URLPRJID)) {
            sb.append("input").append(i).append("_urlprjid");
        } else if (tag.contains(VPRJID)) {
            sb.append("input").append(i).append("_vprjid");
        } else if (tag.contains(PROJECTNAME)) {
            sb.append("input").append(i).append("_projectname");
        } else if (tag.contains(PROJECTCODE)) {
            sb.append("input").append(i).append("_projectcode");
        } else if (tag.contains(BUILDUNIT)) {
            sb.append("input").append(i).append("_buildunit");
        } else if (tag.contains(SUPERVISIONUNIT)) {
            sb.append("input").append(i).append("_supervisionunit");
        } else if (tag.contains(EPCUNIT)) {
            sb.append("input").append(i).append("_epcunit");
        } else if (tag.contains(CONSTRUCTIONUNIT)) {
            sb.append("input").append(i).append("_constructionunit");
        } else if (tag.contains(DESIGNUNIT)) {
            sb.append("input").append(i).append("_designunit");
        } else if (tag.contains(SURVEYUNIT)) {
            sb.append("input").append(i).append("_surveyunit");
        } else if (tag.contains(DETECTAGENCY)) {
            sb.append("input").append(i).append("_detectagency");
        } else if (tag.contains(QUALITYDETECTAGENCY)) {
            sb.append("input").append(i).append("_qualitydetectagency");
        } else if (tag.contains(UNITPROJECT)) {
            sb.append("input").append(i).append("_unitproject");
        } else if (tag.contains(DATETIME)) {
            sb.append("date").append(i);
        } else if (tag.contains(CHECKBOX)) {
            sb.append("checkboxs").append(i);
        } else if (tag.contains(SELECT)) {
            sb.append("selects").append(i);
        } else if (tag.contains(FORMCODE)) {
            sb.append("formcode").append(i);
        }
        if (tag.contains(COPY)) {
            sb.append("_c");
            sb2.append("_c");
        }
        list.add(sb.toString());
        list.add(sb2.toString());
        return list;
    }

    /**
     * 根据标识获取替换文本
     *
     * @param tag
     * @param i
     * @return
     */
    public static String getHtmlReplacement(String tag, int i, int y) {
        String classTag = (tag.contains(MUST)) ? "class=\"must\" " : "";
        String disabledTag = (tag.contains(DISABLED)) ? "disabled=\"true\" " : "";
        String maxLengthTag = "";
        Pattern p = Pattern.compile(MAXLENGTH);
        Matcher m = p.matcher(tag);
        if (m.find()) {
            maxLengthTag = "maxlength=\"" + m.group(1) + "\"";
        }
        //一个标签有多个id的处理
        String id1 = getValueId(tag, i).get(0);
        String id2 = getValueId(tag, i).get(1);
        String htmlReplacement = "";
        if (tag.contains(ONEINPUT) || tag.contains(URLPRJID) || tag.contains(VPRJID) || tag.contains(PROJECTNAME)
                || tag.contains(PROJECTCODE) || tag.contains(BUILDUNIT) || tag.contains(SUPERVISIONUNIT) || tag.contains(EPCUNIT)
                || tag.contains(CONSTRUCTIONUNIT) || tag.contains(DESIGNUNIT) || tag.contains(SURVEYUNIT) || tag.contains(DETECTAGENCY)
                || tag.contains(QUALITYDETECTAGENCY) || tag.contains(UNITPROJECT)) {
            htmlReplacement = "><input " + classTag + disabledTag + maxLengthTag + "value=\"\" id=\"" + id1
                    + "\" placeholder=\"\" style=\"width: 100%; border:none;padding-left:5px\"><";
        } else if (tag.contains(MANYINPUT)) {
            htmlReplacement = "><textarea " + classTag + disabledTag + "placeholder=\"\" row=\"3\" id=\"" + id1
                    + "\" style=\"width:100%;padding-left:5px;border:none\"></textarea><";
        } else if (tag.contains(OKINPUT)) {
            htmlReplacement = "><span>×</span><input " + disabledTag + "type=\"radio\" id=\"" + id1
                    + "\" name=\"right" + i + "\" value=\"incorrect\"><span>√</span><input " + disabledTag + "type=\"radio\" id=\"right"
                    + i + "\" name=\"right" + i + "\" value=\"correct\"><";
        } else if (tag.contains(COMPANYSELECT)) {
            htmlReplacement = "><select " + classTag + disabledTag + "id=\""
                    + id1 + "\"><option>四局</option><option>八局</option><option>五局</option></select><";
        } else if (tag.contains(TIMEINPUT)) {
            htmlReplacement = "><input " + classTag + disabledTag + "id=\"" + id1 + "\" type=\"date\" value=\"\"><input "
                    + classTag + disabledTag + "id=\"" + id2 + "\" type=\"date\" value=\"\"><";
        } else if (tag.contains(FILEINPUT)) {
            classTag = (tag.contains("${m}")) ? "class=\"signature must\" " : "class=\"signature\" ";
            htmlReplacement = "><span style='color: white'>签名处" + y + "</span><";
        } else if (tag.contains(RAHKSELECT)) {
            htmlReplacement = "><select " + classTag + disabledTag + "id=\"" + id1
                    + "\"><option>优良</option><option>合格</option><option>不合格</option></select><";
        } else if (tag.contains(DATETIME)) {
            htmlReplacement = "><input " + classTag + disabledTag + "id=\"" + id1
                    + "\" type=\"date\" value=\"\"><";
        } else if (tag.contains(CHECKBOX)) {
            //去除字符串中所有空格
            String str = StringUtils.deleteWhitespace(tag);
            //切除前后的"${checkbox("和")}"(使用替换空字符串法切除)
            String str1 = StringUtils.replaceOnce(str, ">${checkbox(", "");
            String str2 = StringUtils.replaceOnce(str1, ")}<", "");
            //切除","得到目标字符串数组
            String[] strings = StringUtils.split(str2, ",");
            //遍历字符串数组，拼接解析结果（先把中间的内容遍历拼接好，最后再将两头的">"和"<"一拼就ok了）
            //定义一个用于拼接动态内容的字符串变量
            String str3 = "";
            //先把中间的动态内容遍历拼接好
            for (int k = 0; k < strings.length; k++) {
                str3 += "<input " + disabledTag + "type=\"checkbox\"" + "name=\"right2" + i
                        + "\" value=\"choose\" id=\"check" + k + "\">" + "<span>" + strings[k] + "</span>";
            }
            //最后再将两头的">"和"<"一拼
            htmlReplacement = ">" + str3 + "<";
        } else if (tag.contains(SELECT)) {
            //去除字符串中所有空格
            String str = StringUtils.deleteWhitespace(tag);
            //切除前后的"${select("和")}"(使用替换空字符串法切除)
            String str1 = StringUtils.replaceOnce(str, ">${select(", "");
            String str2 = StringUtils.replaceOnce(str1, ")}<", "");
            //切除","得到目标字符串数组
            String[] strings = StringUtils.split(str2, ",");
            //遍历字符串数组，拼接解析结果（先把中间的内容遍历拼接好，最后再将两头的">"和"<"一拼就ok了）
            //定义一个用于拼接动态内容的字符串变量
            String str3 = "";
            //先把中间的动态内容遍历拼接好
            for (int k = 0; k < strings.length; k++) {
                str3 += "<option>" + strings[k] + "</option>";
            }
            //最后再将两头的">"和"<"一拼
            htmlReplacement = "><select " + classTag + disabledTag + "id=\"" + id1 + "\">" + str3 + "<";
        } else if (tag.contains(FORMCODE)) {
            htmlReplacement = "><span id=\"formcode\"></span><";
        }
        return htmlReplacement;
    }



    /**
     * 获取表头
     *
     * @param text
     * @return
     */
    public static String getTableHead(String text) {
        String rgex = "(>(.*?)</td>)";
        String res = "工程表";
        Pattern pattern = Pattern.compile(rgex);
        Matcher findmatcher = pattern.matcher(text);
        if (findmatcher.find()) {
            res = findmatcher.group(2);
        }
        int n = res.lastIndexOf(">");
        res = res.substring(n + 1, res.length());
        return res;
    }

    /**
     * 保存成默认值或提示信息
     */
    public static String saveValue(Map<String, String> map, String htmlData) {
        //默认值
        if (VALUETAG.equals(map.get(SAVETAG))) {
            String rgex = "( value=\".*?\")";
            Pattern pattern = Pattern.compile(rgex);
            Matcher findmatcher = pattern.matcher(htmlData);
            while (findmatcher.find()) {
                htmlData = findmatcher.replaceAll("");
            }
            htmlData = htmlData.replace(" selected=\"selected\"", "")
                    .replace(" checked", "");
            htmlData = htmlData.replace("×</span><input", "×</span><input value=\"incorrect\"")
                    .replace("√</span><input", "√</span><input value=\"correct\"");
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (htmlData.contains(entry.getKey())) {
                    Boolean a = !"".equals(entry.getValue()) && (entry.getKey().contains("company") || entry.getKey().contains("rank"));
                    if (a) {
                        String rgex3 = "(" + entry.getKey() + "\"" + ".*?" + entry.getValue() + ")";
                        Pattern pattern3 = Pattern.compile(rgex3);
                        Matcher findmatcher3 = pattern3.matcher(htmlData);
                        while (findmatcher3.find()) {
                            String replace3 = findmatcher3.group(1)
                                    .replace("<option>" + entry.getValue(), "<option selected=\"selected\">" + entry.getValue());
                            htmlData = findmatcher3.replaceAll(replace3);
                        }
                    } else if (!"".equals(entry.getValue()) && entry.getKey().contains("right")) {
                        htmlData = htmlData.replace("value=\"" + entry.getValue() + "\"" + " type=\"radio\" id=\"" + entry.getKey() + "\"",
                                "value=\"" + entry.getValue() + "\"" + " type=\"radio\" id=\"" + entry.getKey() + "\"" + " checked");
                    } else if (!"".equals(entry.getValue()) && entry.getKey().contains("previewImg")) {
                        htmlData = htmlData.replace("id=\"" + entry.getKey() + "\"", "id=\"" + entry.getKey() + "\" src=\"" + entry.getValue() + "\"");
                    } else if (!"".equals(entry.getValue()) && entry.getKey().contains("textarea")) {
                        continue;
                    } else {
                        htmlData = htmlData.replace(entry.getKey() + "\"", entry.getKey() + "\" value=\"" + entry.getValue() + "\"");
                    }

                }
            }
            //提示信息
        } else {
            String rgex2 = "( placeholder=\".*?\")";

            Pattern pattern2 = Pattern.compile(rgex2);
            Matcher findmatcher2 = pattern2.matcher(htmlData);
            while (findmatcher2.find()) {
                htmlData = findmatcher2.replaceAll("");
            }
            for (Map.Entry<String, String> entry : map.entrySet()) {
                Boolean b = htmlData.contains(entry.getKey()) &&
                        (entry.getKey().contains("input") || entry.getKey().contains("textarea"));
                if (b) {
                    htmlData = htmlData.replace(entry.getKey() + "\"", entry.getKey() + "\" placeholder=\"" + entry.getValue() + "\"");
                }
            }
        }
        return htmlData;
    }


}
